package com.idc.resource.util;

import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * 阿里云短信工具类
 * Created by Administrator on 2017/7/16 0016.
 */
public class AliCloudSmsUtil {

    /**
     * 进行url编码
     * @param value 需要编码的值
     * @return 编码后的值
     */
    public static String specialUrlEncode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    /**
     * HmacSHA1 签名
     * @param accessSecret 密钥
     * @param stringToSign 需要签名的串
     * @return 签名结果
     */
    public static String sign(String accessSecret, String stringToSign) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new BASE64Encoder().encode(signData);
    }
}
